<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
const emit = defineEmits(['update:value', 'update:enable'])
const props = withDefaults(defineProps<{ value: string; enable: boolean }>(), {})

const state = ref(false)
const newValue = ref('')
watch(
  () => props.value,
  (value: string) => {
    newValue.value = value
  },
  {
    immediate: true,
    deep: true
  }
)

const shotKeyInput = ref<HTMLInputElement>()
const changeState = () => {
  if (!props.enable) return
  state.value = true
  nextTick(() => {
    if (state.value) shotKeyInput?.value?.focus()
  })
}
</script>

<template>
  <div
    class="bind-key h-full flex items-center justify-center gap-2"
    :class="{
      'cursor-not-allowed': !enable
    }"
  >
    <div class="flex-1 h-full flex items-center" @click="changeState">
      <el-input
        v-if="state"
        ref="shotKeyInput"
        v-model="newValue"
        placeholder="请绑定快捷键"
        :disabled="!enable"
        clearable
        class="h-8"
        @input="(e: string) => emit('update:value', e)"
        @blur="state = false"
      />
      <div
        v-else
        class="w-full flex items-center justify-center border border-solid border-slate-200 h-8 text-sm rounded-md overflow-hidden"
        :class="{
          'bg-[rgba(151,147,147,0.3)]': !enable
        }"
      >
        {{ newValue }}
      </div>
    </div>
    <div :title="enable ? '禁用' : '启用'">
      <svg-icon
        :width="20"
        :height="20"
        :name="enable ? 'disable' : 'enable'"
        :fill="enable ? '#d81e06' : '#1afa29'"
        class="cursor-pointer"
        @click="emit('update:enable', !enable)"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-input) {
  .el-input__wrapper {
    .el-input__inner {
      @apply text-center;
    }
    .el-input__suffix {
      @apply absolute right-2;
    }
  }
}
</style>
